package com.kgc.itrip.search.dao;

import com.kgc.itrip.tuils.common.EmptyUtils;
import com.kgc.itrip.tuils.common.Page;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.impl.XMLResponseParser;
import org.apache.solr.client.solrj.response.QueryResponse;

import java.io.IOException;
import java.util.List;

/**
 * test
 * @param <T>
 */
public class BaseDao2<T> {

    private HttpSolrClient solrClient;

    public BaseDao2(String url) {
        /* 创建对象 */
        solrClient = new HttpSolrClient(url);
        /* 格式化参数 */
        solrClient.setParser(new XMLResponseParser());
        /* 设置过期时间 */
        solrClient.setConnectionTimeout(500);
    }

    public Page queryPage(SolrQuery solrQuery , Integer pageNo,Integer pageSize , Class clazz){
        // 设置页码或者页容量
        Integer currPage = EmptyUtils.isNotEmpty(pageNo) ? pageNo : 1;
        Integer pSize = EmptyUtils.isNotEmpty(pageSize) ? pageSize :5;
        // 设置solr的页码
        solrQuery.setStart((currPage - 1) * pSize);
        solrQuery.setRows(pSize);
        // 获取查询结果
        try {
            QueryResponse query = solrClient.query(solrQuery);
            // 获取总条数
            int intValue = Long.valueOf(query.getResults().getNumFound()).intValue();
            Page page = new Page(currPage, pSize ,intValue);
            List<T> rows = query.getBeans(clazz);
            page.setRows(rows);
            return  page;
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 直接查询列表
     * @param solrQuery
     * @param pageSize
     * @param clazz
     * @return
     */
    public List<T> queryList(SolrQuery solrQuery , Integer pageSize , Class clazz){
        if(EmptyUtils.isNotEmpty(pageSize)){
            solrQuery.setStart(0);
            solrQuery.setRows(pageSize);
        }
        try {
            QueryResponse query = solrClient.query(solrQuery);
            return query.getBeans(clazz);
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
